import ctypes
import logging
import platform
import sys

import pandas as pd
from PySide6 import QtWidgets
from PySide6.QtGui import QAction
from PySide6.QtNetwork import QLocalSocket, QLocalServer
from PySide6.QtWidgets import QMainWindow, QToolBar, QMessageBox

import kumquat_king_pyside6.app_config as app_config
from kumquat_king_pyside6.controls.apis import get_kumquat_format, get_presenters
from kumquat_king_pyside6.pages.add_order_page import AddOrderPage
from kumquat_king_pyside6.pages.manage_kumquat_page import KumquatManagePage
from kumquat_king_pyside6.pages.view_orders_page import ViewOrderPage
from kumquat_king_pyside6.tools import message_box, basic_log_config

logger = None


class MainFrame(QMainWindow):
    def __init__(self):
        super(MainFrame, self).__init__()
        self.init_args()
        self.init_ui()
        self.init_slots()
        self.init_status()

    def init_ui(self):
        sys = platform.system()
        if sys == "Windows":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                app_config.APP_NAME)
        self.resize(1500, 900)

        self.setWindowTitle(app_config.APP_NAME)
        self.stacks = QtWidgets.QStackedWidget()

        # Menubar
        self.menubar = self.menuBar()
        self.menuFile = self.menubar.addMenu('文件')
        self.loadFromFileAction = QAction('从文件导入订单')
        self.genExcelFileAction = QAction('生成对应格式Excel')
        self.menuFile.addAction(self.loadFromFileAction)
        self.menuFile.addAction(self.genExcelFileAction)
        self.menubar.addAction(self.menuFile.menuAction())

        self.toolBar = QToolBar('test tool bar', self)
        self.addToolBar(self.toolBar)
        self.addOrderAction = QAction('新增订单')
        self.showOrderAction = QAction('订单管理')
        self.kumquatAction = QAction('金桔价格')

        self.toolBar.addAction(self.addOrderAction)
        self.toolBar.addAction(self.showOrderAction)
        self.toolBar.addAction(self.kumquatAction)

        # ADD ORDER STACK LAYOUT
        self.addOrderStack = AddOrderPage(None, self.baseInfo['kumquatFormat'])
        self.viewOrderStack = ViewOrderPage(self.baseInfo['kumquatFormat'], self.baseInfo['presenters'])
        self.kumquatManageStack = KumquatManagePage()

        # ADD ALL TO MAIN UI
        self.stacks.addWidget(self.addOrderStack)
        self.stacks.addWidget(self.viewOrderStack)
        self.stacks.addWidget(self.kumquatManageStack)
        self.setCentralWidget(self.stacks)
        self.stacks.setCurrentWidget(self.addOrderStack)
        # self.setStyleSheet(app_config.STYLE_SHEET)

    def init_args(self):
        resCode, kumquatFormat = get_kumquat_format()
        if resCode not in [200, 201]:
            message_box("错误", "金桔格式获取失败： " + kumquatFormat)
        resCode, presenters = get_presenters()
        if resCode not in [200, 201]:
            message_box("错误", "线人获取失败： " + presenters)
        self.baseInfo = {"kumquatFormat": kumquatFormat[0]['data'], "presenters": presenters[0]['data']}
        logging.info(get_kumquat_format())
        logging.info(get_presenters())

    def init_slots(self):
        self.addOrderAction.triggered.connect(lambda: self.set_stacks(self.addOrderAction))
        self.showOrderAction.triggered.connect(lambda: self.set_stacks(self.showOrderAction))
        self.kumquatAction.triggered.connect(lambda: self.set_stacks(self.kumquatAction))
        self.genExcelFileAction.triggered.connect(self.generate_excel_file)
        self.loadFromFileAction.triggered.connect(self.addOrderStack.load_from_file)

    def init_status(self):
        pass

    def set_stacks(self, sender):
        if sender == self.addOrderAction:
            logging.info("切换到新增订单页: " + self.addOrderStack.objectName())
            self.stacks.setCurrentWidget(self.addOrderStack)
            self.addOrderAction.setEnabled(False)
            self.showOrderAction.setEnabled(True)
            self.kumquatAction.setEnabled(True)

        elif sender == self.showOrderAction:
            logging.info("切换到查看订单页: " + self.showOrderAction.objectName())
            self.stacks.setCurrentWidget(self.viewOrderStack)
            self.addOrderAction.setEnabled(True)
            self.showOrderAction.setEnabled(False)
            self.kumquatAction.setEnabled(True)

        elif sender == self.kumquatAction:
            logging.info("切换到查看金桔页: " + self.kumquatAction.objectName())
            self.stacks.setCurrentWidget(self.kumquatManageStack)
            self.addOrderAction.setEnabled(True)
            self.showOrderAction.setEnabled(True)
            self.kumquatAction.setEnabled(False)

    def generate_excel_file(self):
        expectedFilePath = QtWidgets.QFileDialog.getSaveFileName(self, "保存文件", "./data", "Excel 文件 (*.xlsx)")
        if expectedFilePath[0] == '':
            return
        else:
            df = pd.DataFrame(app_config.ORDER_EXCEL_SAMPLE_DATA, columns=app_config.ORDER_EXCEL_HEADERS)
            df.to_excel(expectedFilePath[0], index=False)
            msbox = QMessageBox()
            msbox.setWindowTitle("提示")
            msbox.setText("已生成文件： " + expectedFilePath[0])
            msbox.exec()


def main():
    basic_log_config(app_config.LOG_DIR, False)
    app = QtWidgets.QApplication(sys.argv)
    app_name = app_config.APP_NAME
    logging.info("启动程序....")
    try:
        socket = QLocalSocket()
        socket.connectToServer(app_name)
        if socket.waitForConnected(500):
            message_box("错误", "该程序正在运行中！")
            app.quit()
        else:
            local_server = QLocalServer()
            local_server.listen(app_name)
            main_window = MainFrame()
            main_window.show()
            sys.exit(app.exec())
    except Exception as e:
        import traceback

        traceback.print_exc()
        message_box("错误", "启动失败： " + str(e))
